const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
const serve = require('koa-static-server');
const router = new Router();
const compareVersions = require('compare-versions');


function getNewVersion(version) {
    if (!version) return null;
    let maxVersion = {
        name: '0.0.4',
        pub_date: '2019-03-05',
        notes: "新增功能AAA",
        url: ''
    }

    if (compareVersions.compare(maxVersion.name, version, '>')) {
        return maxVersion;
    }
    return null;
}

router.get('/', async (ctx, next) => {
    ctx.body = 'Hello World';
});

// mac 更新
// http://localhost:8888/darwin?version=0.0.1
router.get('/darwin', async (ctx, next) => {
    // 处理Mac更新 ?version=1.0.0&uid=123
    let { version } = ctx.query;
    let newVersion = getNewVersion(version);
    if (newVersion) {
        ctx.body = newVersion;
    } else {
        ctx.body = {
            code: 0,
            msg: '没有新版本'
        }
    }
});

// // windows 更新
router.get('/win32/RELEASES', (ctx, next) => {
    // 处理windows更新 ?version=1.0.0&uid=123
    let { version } = ctx.query;
    console.log('server is running at http://localhost:8888');
    let newVersion = getNewVersion(version);
    if (newVersion) {
        ctx.body = '0BBAE0117C22CFC0C7C794776FEE5073F8D55186 data-safe-bin-0.0.2-full.nupkg 110716479';
    } else {
        ctx.body = {
            code: 0,
            msg: '没有新版本'
        }
    }
})

// router.get('/win32/*.nupkg', (ctx, next) => {
//     // redirect s3 静态文件服务
//     ctx.redirect(`/public/${ctx.params[0]}.nupkg`)
// })

router.get('/win32/(.*)\\.nupkg', (ctx, next) => {
    // 注意：在正则表达式中，你需要对点（.）进行转义，因为它在正则表达式中有特殊含义
    // ctx.params[0] 现在将包含文件名（不含路径和扩展名）
    const fileName = ctx.params[0];
    console.log('server is running at http://localhost:8888');
    // 假设你的 S3 服务期望的 URL 路径是 /public/ 加上文件名和 .nupkg 扩展名
    ctx.redirect(`/public/${fileName}.nupkg`);
});

app.use(serve({ rootDir: 'public', rootPath: '/public' }))
app.use(router.routes()).use(router.allowedMethods())

app.listen(8888, () => {
    console.log('server is running at http://localhost:8888/public/data-safe-bin-0.0.2-full.nupkg');
});
